<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>服务守护</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="./css/elementUI.css">
  <!-- import Vue before Element -->
  <script src="./js/vue.min.js"></script>
  <!-- 引入组件库 -->
  <script src="./js/elementUI.js"></script>
  <script src="./js/axios.min.js"></script>

  <style>
    body, html {
      margin: 0;
    }

    #app {
      height: 100vh;
      width: 100vw;
    }

    .el-tabs {
      display: flex;
      flex-direction: column;
      height: 100%;
      box-sizing: border-box;
    }

    .el-tabs__header {
      box-sizing: border-box;
    }

    .el-tabs__content {
      flex: 1;
    }
  </style>
</head>
<body>
<div id="app">
  <el-tabs type="border-card">
    <el-tab-pane label="服务器管理">
      <el-button @click="addServerVisible = true">新增服务器</el-button>
      <el-table
        :data="serverList"
        style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="50">
        </el-table-column>
        <el-table-column
          prop="name"
          label="服务器名称">
        </el-table-column>
        <el-table-column
          label="主机">
          <template slot-scope="{row}">
            {{ row.host }}:{{ row.port }}
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名">
        </el-table-column>
        <el-table-column
          label="密码">
          <template slot-scope="{row}">
            ********
          </template>
        </el-table-column>
        <el-table-column
          label="管理">
          <template slot-scope="{row}">
            <el-button size="mini" type="danger" @click="deleteServer(row)">删除</el-button>
            <el-button size="mini" type="primary" @click="editServer(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="服务管理">
      <el-button @click="addServiceVisible = true">新增服务</el-button>
      <el-table
        :data="serviceList"
        style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="50">
        </el-table-column>
        <el-table-column
          prop="name"
          label="服务名称">
        </el-table-column>
        <el-table-column
          prop="host"
          label="服务器名称">
          <template slot-scope="{row}">
            {{ row.server.name }}
          </template>
        </el-table-column>
        <el-table-column
          prop="path"
          label="目录">
        </el-table-column>
        <el-table-column
          prop="fileName"
          label="文件名">
        </el-table-column>
        <el-table-column
          prop="startCommand"
          label="启动命令">
        </el-table-column>
        <el-table-column
          width="480"
          label="管理">
          <template slot-scope="{row}">
            <el-button size="mini" type="danger" @click="deleteService(row)">删除</el-button>
            <el-button size="mini" type="primary" @click="editService(row)">编辑</el-button>
            <el-button size="mini" type="primary" @click="openUpdateServiceBox(row)">升级</el-button>

            <el-button size="mini" type="primary" @click="startService(row)" :disabled="row.status!=='closed'">启动
            </el-button>
            <el-button size="mini" type="danger" @click="stopService(row)" :disabled="row.status!=='started'">停止
            </el-button>
            <el-button size="mini" type="warning" @click="restartService(row)" :disabled="row.status!=='started'">重启
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>

  <el-dialog :close-on-click-modal="false" width="500px"
             :visible.sync="updateServiceVisible" title="升级服务">
    <el-form ref="form" :model="updateServiceForm" label-width="80px">
      <el-form-item label="服务">
        <el-select :disabled="true" v-model="updateServiceForm.id" placeholder="请选择服务">
          <el-option :label="item.name" :value="item.id" v-for="item in serviceList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文件">
        <el-upload
          ref="upload"
          drag
          :action="`${serverAddress}/manager/updateServerById`"
          :data="updateServiceForm"
          accept=""
          :on-success="onUpdateSucc"
          name="jarFile"
          :auto-upload="false">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jar文件，且不超过1000MB</div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateServiceFile">立即更新</el-button>
        <el-button @click="closeUpdateServiceBox">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog :close-on-click-modal="false" width="500px"
             :visible.sync="addServiceVisible" :title="(addServerForm.id?'编辑':'新增')+'服务'">
    <el-form ref="form" :model="addServiceForm" label-width="80px">
      <el-form-item label="名称">
        <el-input v-model="addServiceForm.name"></el-input>
      </el-form-item>
      <el-form-item label="服务器">
        <el-col :span="15">
          <el-select v-model="addServiceForm.server.id" placeholder="请选择服务器">
            <el-option :label="item.name" :value="item.id" v-for="item in serverList" :key="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button @click="addServerVisible = true" title="新增服务器">+</el-button>
        </el-col>
      </el-form-item>
      <el-form-item label="目录">
        <el-input v-model="addServiceForm.path"></el-input>
      </el-form-item>
      <el-form-item label="文件名">
        <el-input v-model="addServiceForm.fileName"></el-input>
      </el-form-item>
      <el-form-item label="启动命令">
        <el-input v-model="addServiceForm.startCommand"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addService">立即{{addServiceForm.id ? '修改' : '添加'}}</el-button>
        <el-button @click="closeAddServiceBox">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog :close-on-click-modal="false" width="500px"
             :visible.sync="addServerVisible" :title="(addServerForm.id?'编辑':'新增')+'服务器'">
    <el-form ref="form" :model="addServerForm" label-width="80px">
      <el-form-item label="名称">
        <el-input v-model="addServerForm.name"></el-input>
      </el-form-item>
      <el-form-item label="主机">
        <el-input v-model="addServerForm.host"></el-input>
      </el-form-item>
      <el-form-item label="端口">
        <el-input v-model="addServerForm.port"></el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="addServerForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="addServerForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addServer">立即{{addServerForm.id ? '修改' : '添加'}}</el-button>
        <el-button @click="closeAddServerBox">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</div>
</body>
<script>
  // const serverAddress = "http://192.168.7.124:8082"
  const serverAddress = location.origin

  // 添加响应拦截器
  axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    let data = response.data;
    if (data.code === "0") {
      return data.data;
    } else {
      return Promise.reject(new Error(data.message));
    }
  }, function (error) {
    // 对响应错误做点什么
    console.log(error)
    return Promise.reject(error);
  });

  new Vue({
    el: '#app',
    data() {
      return {
        serverAddress,
        serverList: [],
        serviceList: [],
        addServerVisible: false,
        addServerForm: {
          id: '',
          name: '',
          host: '',
          port: 22,
          username: '',
          password: ''
        },
        addServiceVisible: false,
        addServiceForm: {
          id: '',
          name: '',
          server: {
            id: ''
          },
          path: "",
          fileName: '',
          startCommand: ''
        },
        updateServiceVisible: false,
        updateServiceForm: {
          id: ''
        }
      }
    },
    async mounted() {
      this.getServerList()
      await this.getServiceList()
      this.getServiceListStatus()
    },
    methods: {
      getServiceListStatus() {
        for (let i = 0; i < this.serviceList.length; i++) {
          let service = this.serviceList[i]
          this.getServiceStatus(service)
        }
        setTimeout(this.getServiceListStatus, 5000)
      },
      async getServiceStatus(service) {
        let res = await axios.post(`${serverAddress}/manager/isServerStartedByid`, {id: service.id})
        this.$set(service, "status", res ? "started" : "closed")
      },
      async getServerList() {
        this.serverList = await axios.post(`${serverAddress}/server/getServerList`)
      },
      async getServiceList() {
        this.serviceList = await axios.post(`${serverAddress}/service/getServiceList`)
      },
      async addServer() {
        try {
          let url = `${serverAddress}/server`
          if (this.addServerForm.id) {
            url += "/updateServer";
          } else {
            url += "/addServer";
          }
          let res = await axios.post(url, this.addServerForm)
          if (res === 1) {
            this.$message.success('添加成功');
          } else {
            this.$message.error('添加失败');
          }
          this.closeAddServerBox()
          this.getServerList()
        } catch (e) {
          this.$alert('失败原因：' + e.message, '失败')
        }
      },
      async addService() {
        try {
          let url = `${serverAddress}/service`
          if (this.addServiceForm.id) {
            url += "/updateService";
          } else {
            url += "/addService";
          }
          let res = await axios.post(url, this.addServiceForm)
          if (res === 1) {
            this.$message.success('添加成功');
          } else {
            this.$message.error('添加失败');
          }
          this.closeAddServiceBox()
          this.getServiceList()
        } catch (e) {
          this.$alert('失败原因：' + e.message, '失败')
        }
      },
      closeAddServerBox() {
        this.addServerVisible = false;
        this.addServerForm = {
          id: '',
          name: '',
          host: '',
          port: 22,
          username: '',
          password: ''
        }
      },
      closeAddServiceBox() {
        this.addServiceVisible = false;
        this.addServiceForm = {
          id: '',
          name: '',
          server: {
            id: ''
          },
          path: "",
          fileName: '',
          startCommand: ''
        }
      },
      async deleteServer(server) {
        try {
          await this.$confirm('是否删除？删除后将无法恢复。', '确认', {
            type: 'warning'
          });
        } catch (e) {
          return
        }
        try {
          let res = await axios.post(`${serverAddress}/server/delServer`, {id: server.id})
          if (res === 1) {
            this.$message.success('删除成功');
          } else {
            this.$message.error('删除失败');
          }
          this.getServerList()
        } catch (e) {
          this.$alert('失败原因：' + e.message, '失败')
        }
      },
      async deleteService(service) {
        try {
          await this.$confirm('是否删除？删除后将无法恢复。', '确认', {
            type: 'warning'
          });
        } catch (e) {
          return
        }
        try {
          let res = await axios.post(`${serverAddress}/service/delService`, {id: service.id})
          if (res === 1) {
            this.$message.success('删除成功');
          } else {
            this.$message.error('删除失败');
          }
          this.getServiceList()
        } catch (e) {
          this.$alert('失败原因：' + e.message, '失败')
        }
      },
      async editServer(server) {
        this.addServerForm = JSON.parse(JSON.stringify(server))
        this.addServerVisible = true
      },
      async editService(service) {
        this.addServiceForm = JSON.parse(JSON.stringify(service))
        this.addServiceVisible = true
      },
      async startService(service) {
        try {
          let res = await axios.post(`${serverAddress}/manager/startServerById`, {id: service.id})
          if (res) {
            this.$message.success('启动成功');
          } else {
            this.$message.error('启动失败');
          }
        } catch (e) {
          this.$alert('失败原因：' + e.message, '失败')
        }
      },
      async stopService(service) {
        try {
          let res = await axios.post(`${serverAddress}/manager/stopServerById`, {id: service.id})
          if (res) {
            this.$message.success('停止成功');
          } else {
            this.$message.error('停止失败');
          }
        } catch (e) {
          this.$alert('失败原因：' + e.message, '失败')
        }
      },
      async restartService(service) {
        try {
          let res = await axios.post(`${serverAddress}/manager/restartServerById`, {id: service.id})
          if (res) {
            this.$message.success('重启成功');
          } else {
            this.$message.error('重启失败');
          }
        } catch (e) {
          this.$alert('失败原因：' + e.message, '失败')
        }
      },
      async updateServiceFile() {
        this.$refs.upload.submit();
      },
      openUpdateServiceBox(service) {
        this.updateServiceVisible = true
        this.updateServiceForm.id = service.id
      },
      closeUpdateServiceBox() {
        this.updateServiceVisible = false
        this.updateServiceForm = {
          id: ''
        }
      },
      onUpdateSucc(response, file, fileList) {
        if (response.success) {
          if (response.data) {
            this.$message.success('升级成功');
            this.closeUpdateServiceBox();
          } else {
            this.$message.error('升级失败');
          }
        } else {
          this.$alert('失败原因：' + response.message, '失败')
        }
      }
    }
  })
</script>
</html>